﻿using MaterialDesignThemes.Wpf;
using Microsoft.Win32;
using StudentInfoSystem.Core.Interfaces;
using StudentInfoSystem.Core.Models;
using StudentInfoSystem.UI.Services;
using StudentInfoSystem.UI.Views;
using StudentInfoSystem.UI.Views.Dialogs;
using StudentInfoSystem.UI.Views.Pages;
using StudentInfoSystem.UI.Views.Windows;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using System.Windows.Media.Effects;
using System.Windows.Threading;
using static StudentInfoSystem.UI.Views.Windows.LoginWindow;

namespace StudentInfoSystem.UI.Views.Component;

public partial class TitleBar : UserControl
{
    private DispatcherTimer _clockTimer; // 添加计时器字段
    public TitleBar()
    {
        InitializeComponent();
        SetThemeIcon(AppSettings.Instance.IsDarkTheme);
        _clockTimer = InitializeClock();
    }

    // 窗口控制事件
    public event RoutedEventHandler? MinimizeClicked;
    public event RoutedEventHandler? MaximizeClicked;
    public event RoutedEventHandler? CloseClicked;

    private void Minimize_Click(object sender, RoutedEventArgs e) =>
        MinimizeClicked?.Invoke(this, e);

    private void Maximize_Click(object sender, RoutedEventArgs e) =>
        MaximizeClicked?.Invoke(this, e);

    private void Close_Click(object sender, RoutedEventArgs e) =>
        CloseClicked?.Invoke(this, e);

    // 更新时间显示
    private void UpdateTimeDisplay()
    {
        TimeDisplay.Text = DateTime.Now.ToString("yyyy年MM月dd日 HH:mm");
    }

    private DispatcherTimer InitializeClock()
    {
        // 初始化时钟
        UpdateTimeDisplay();

        // 设置每分钟更新一次的计时器
        _clockTimer = new DispatcherTimer
        {
            Interval = TimeSpan.FromMinutes(1)
        };
        _clockTimer.Tick += (s, e) => UpdateTimeDisplay();
        _clockTimer.Start();
        return _clockTimer;
    }

    // 切换主题
    private void ThemeToggle_Click(object sender, RoutedEventArgs e)
    {
        var newTheme = !AppSettings.Instance.IsDarkTheme;
        AppSettings.Instance.IsDarkTheme = newTheme;
        SetThemeIcon(newTheme);
    }

    // 更新方法，用于设置正确的图标
    public void SetThemeIcon(bool isDarkTheme)
    {
        // 异步切换避免UI阻塞
        Application.Current.Dispatcher.InvokeAsync(() =>
        {
            ThemeService.ApplyTheme(isDarkTheme);
        });
        ThemeIcon.Kind = isDarkTheme ? PackIconKind.WeatherSunny : PackIconKind.WeatherNight;
    }

    public event RoutedEventHandler? UserAvatarClicked;

    // 头像点击事件处理
    private void AvatarButton_Click(object sender, RoutedEventArgs e)
    {
        // 检查是否已登录（当前会话用户或记住的用户）
        bool isLoggedIn = AppSettings.Instance.CurrentUser != null;
        var loginWindow = new LoginWindow
        {
            IsDuringStartup = false,
            Owner = Application.Current.MainWindow,
            WindowStartupLocation = WindowStartupLocation.CenterOwner
        };
        // 确保传递当前用户状态
        loginWindow._currentUser = AppSettings.Instance.CurrentUser;
        // 确保正确订阅 LoginOut 事件
        loginWindow.LoginOut += () =>
        {
            // 直接调用隐藏主窗口的方法
            Application.Current.Dispatcher.Invoke(() =>
            {
                if (Application.Current.MainWindow != null)
                {
                    Application.Current.MainWindow.Hide();
                }
            });
        };

        // 确保正确订阅 LoginOut 事件
        loginWindow.LoginSuccess += (user) =>
        {
            // 直接调用隐藏主窗口的方法
            Application.Current.Dispatcher.Invoke(() =>
            {
                if (Application.Current.MainWindow != null)
                {
                    Application.Current.MainWindow.Show();
                }
            });
        };
        if (isLoggedIn)
        {
            // 已登录，显示用户信息卡片
            ShowUserInfoDialog(loginWindow);
        }
        else
        {
            // 未登录，显示登录窗口
            ShowLoginDialog(loginWindow);
        }
    }


    // 显示用户信息对话框
    private void ShowUserInfoDialog(LoginWindow loginWindow)
    {
        // 设置当前用户，以便显示正确的用户信息
        loginWindow._currentUser = AppSettings.Instance.CurrentUser;

        loginWindow.ShowUserInfo();
        loginWindow.ShowDialog();
    }


    // 显示登录对话框
    private void ShowLoginDialog(LoginWindow loginWindow)
    {
        // 显示账户选择而不是直接显示登录窗口
        if (AppSettings.Instance.UserAccounts.Count > 0)
        {
            loginWindow.ShowAccountSelection();
        }
        else
        {
            loginWindow.ShowDialog();
        }
    }

    private void LogButton_Click(object sender, RoutedEventArgs e)
    {
        // 检查是否为管理员
        if (AppSettings.Instance.CurrentUser?.IsAdmin != true)
        {
            MessageBox.Show("只有管理员可以查看日志", "权限不足", MessageBoxButton.OK, MessageBoxImage.Warning);
            return;
        }

        // 获取日志目录路径
        string logDir = Path.Combine("Logs");

        // 修改为直接在当前程序目录查找 logs.exe
        string exePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs.exe");

        // 确保日志目录存在
        Directory.CreateDirectory(logDir);

        if (File.Exists(exePath))
        {
            // 使用双引号包裹路径确保空格正确处理
            Process.Start(exePath, $"\"{logDir}\"");
        }
        else
        {
            // 文件不存在时显示警告框
            MessageBox.Show("找不到 logs.exe 程序，请确保它位于当前程序目录中。",
                            "文件缺失",
                            MessageBoxButton.OK,
                            MessageBoxImage.Warning);
        }
    }


    // 添加菜单事件处理
    private void MenuItem_Exit_Click(object sender, RoutedEventArgs e)
    {
        Application.Current.Shutdown();
    }

    private void MenuItem_GenerateData_Click(object sender, RoutedEventArgs e)
    {
        var generateWindow = new GenerateDataWindow
        {
            Owner = Application.Current.MainWindow
        };

        if (generateWindow.ShowDialog() == true && !string.IsNullOrEmpty(generateWindow.DatabasePath))
        {
            // 更新数据库路径设置
            AppSettings.Instance.SavedDataBasePath = generateWindow.DatabasePath;

            // 触发数据库重新加载事件
            DatabasePathChanged?.Invoke(this, generateWindow.DatabasePath);
        }
    }

    private void MenuItem_NewDatabase_Click(object sender, RoutedEventArgs e)
    {
        // 实现新建数据库功能
        SaveFileDialog saveFileDialog = new SaveFileDialog
        {
            Filter = "SQLite 数据库文件 (*.db)|*.db",
            FileName = "NewDatabase.db"
        };

        if (saveFileDialog.ShowDialog() == true)
        {
            // 创建新数据库文件
            File.Create(saveFileDialog.FileName).Close();

            // 更新设置
            AppSettings.Instance.SavedDataBasePath = saveFileDialog.FileName;

            // 触发数据库重新加载事件
            DatabasePathChanged?.Invoke(this, saveFileDialog.FileName);
        }
    }

    private void MenuItem_OpenDatabase_Click(object sender, RoutedEventArgs e)
    {
        // 实现打开数据库功能
        OpenFileDialog openFileDialog = new OpenFileDialog
        {
            Filter = "SQLite 数据库文件 (*.db)|*.db",
            CheckFileExists = true
        };

        if (openFileDialog.ShowDialog() == true)
        {
            // 更新设置
            AppSettings.Instance.SavedDataBasePath = openFileDialog.FileName;

            // 触发数据库重新加载事件
            DatabasePathChanged?.Invoke(this, openFileDialog.FileName);
        }
    }

    // 添加数据库路径更改事件
    public event RoutedEventHandler<string> DatabasePathChanged;

    // 用于传递字符串参数的事件处理器
    public delegate void RoutedEventHandler<T>(object sender, T e);


    private void MenuItem_ExportDatabase_Click(object sender, RoutedEventArgs e)
    {
        // 检查是否为管理员
        if (AppSettings.Instance.CurrentUser?.IsAdmin != true)
        {
            MessageBox.Show("只有管理员可以导出数据", "权限不足", MessageBoxButton.OK, MessageBoxImage.Warning);
            return;
        }

        // 创建导出格式选择对话框
        var exportDialog = new ExportFormatDialog();

        if (exportDialog.ShowDialog() == true && exportDialog.SelectedFormat != null)
        {
            // 弹出保存文件对话框
            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Filter = GetExportFilter(exportDialog.SelectedFormat.Value),
                DefaultExt = GetDefaultExtension(exportDialog.SelectedFormat.Value),
                FileName = $"StudentDatabase_{DateTime.Now:yyyyMMdd_HHmmss}"
            };

            if (saveFileDialog.ShowDialog() == true)
            {
                // 触发导出事件
                DatabaseExportRequested?.Invoke(this, (saveFileDialog.FileName, exportDialog.SelectedFormat.Value));
            }
        }
    }

    private string GetExportFilter(ExportFormat format)
    {
        return format switch
        {
            ExportFormat.SQLite => "SQLite数据库文件 (*.db)|*.db|所有文件 (*.*)|*.*",
            ExportFormat.SQLServer => "SQL Server脚本 (*.sql)|*.sql|所有文件 (*.*)|*.*",
            ExportFormat.MySQL => "MySQL脚本 (*.sql)|*.sql|所有文件 (*.*)|*.*",
            ExportFormat.CSV => "CSV文件 (*.csv)|*.csv|所有文件 (*.*)|*.*",
            ExportFormat.JSON => "JSON文件 (*.json)|*.json|所有文件 (*.*)|*.*",
            _ => "所有文件 (*.*)|*.*"
        };
    }

    private string GetDefaultExtension(ExportFormat format)
    {
        return format switch
        {
            ExportFormat.SQLite => ".db",
            ExportFormat.SQLServer => ".sql",
            ExportFormat.MySQL => ".sql",
            ExportFormat.CSV => ".csv",
            ExportFormat.JSON => ".json",
            _ => ".txt"
        };
    }

    // 添加数据库导出请求事件
    public event EventHandler<(string FilePath, ExportFormat Format)> DatabaseExportRequested;
}